package com.fzg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fzg.common.enums.ResponseWrapper;
import com.fzg.common.tool.JwtUtil;
import com.fzg.entity.UserCollect;
import com.fzg.mapper.UserCollectMapper;
import com.fzg.service.UserCollectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author fzg
 * @since 2022-07-05
 */
@Service
public class UserCollectServiceImpl extends ServiceImpl<UserCollectMapper, UserCollect> implements UserCollectService {

    @Autowired
    private UserCollectMapper userCollectMapper;

    /**
     * 当前登陆的用户收藏日记
     *
     * @param diaryAid 日记aid
     * @return ResponseWrapper
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseWrapper currentUserCollectCurrentDiary(HttpServletRequest request, Integer diaryAid) {
        userCollectMapper.insert(new UserCollect(){{
            setUserAid(JwtUtil.getTokenId(request.getHeader("token")));
            setCollectType(1);
            setContentAid(diaryAid);
        }});
        return ResponseWrapper.markSuccess();
    }

    /**
     * 当前登陆的用户取消收藏日记
     *
     * @param request 参数
     * @param diaryAid 参数
     * @return ResponseWrapper
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseWrapper userCancelCollectDiary(HttpServletRequest request, Integer diaryAid) {
        List<UserCollect> collectList = userCollectMapper.selectList(new LambdaQueryWrapper<UserCollect>()
                .eq(UserCollect::getUserAid, JwtUtil.getTokenId(request.getHeader("token")))
                .eq(UserCollect::getCollectType, 1)
                .eq(UserCollect::getContentAid, diaryAid)
        );
        for (UserCollect userCollect : collectList) {
            userCollectMapper.deleteById(userCollect);
        }
        return ResponseWrapper.markSuccess();
    }
}
